<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col>
        <el-card class="box-card">
          <div class="text item">
            提示：目录的组件为Layout，所有路由菜单必须依附于Layout组件显示，
            当Layout目录下之后一个菜单时则只显示该菜单，
            删除目录时应先删除其下所有菜单。
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- TODO 当只有一个子路由时应只显示子路由，所有路由必须归属于 Layout 的路由之下 -->
    <el-table
      v-loading="loading"
      :data="menuList"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="meta.title" label="菜单名称" :show-overflow-tooltip="true" width="160" />
      <el-table-column prop="meta.icon" label="图标" align="center" width="100">
        <template slot-scope="scope">
          <svg-icon :icon-class="handleIcon(scope.row.meta.icon)" />
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="100" />
      <el-table-column prop="component" label="组件路径" :show-overflow-tooltip="true" />
      <el-table-column prop="path" label="路由地址" width="300" />
      <el-table-column prop="redirect" label="重定向地址" width="180" />
      <el-table-column prop="hidden" label="是否隐藏" :formatter="formatter" width="80" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType">
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上级目录">
              <tree-select
                v-model="form.parentId"
                :options="menuOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级菜单"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单图标">
              <el-input v-model="form.meta.icon" placeholder="请输入图标名称" />
              <!-- <el-popover-->
              <!--   placement="bottom-start"-->
              <!--   width="460"-->
              <!--   trigger="click"-->
              <!--   @show="$refs['iconSelect'].reset()"-->
              <!-- >-->
              <!--   <IconSelect ref="iconSelect" @selected="selected" />-->
              <!--   <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标" readonly>-->
              <!--     <svg-icon-->
              <!--       v-if="form.icon"-->
              <!--       slot="prefix"-->
              <!--       :icon-class="form.icon"-->
              <!--       class="el-input__icon"-->
              <!--       style="height: 32px;width: 16px;"-->
              <!--     />-->
              <!--     <i v-else slot="prefix" class="el-icon-search el-input__icon" />-->
              <!--   </el-input>-->
              <!-- </el-popover>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="meta.title">
              <el-input v-model="form.meta.title" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType === 'C'" :span="12">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示状态">
              <el-radio-group v-model="form.hidden">
                <el-radio :label="false">显示</el-radio>
                <el-radio :label="true">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMenuList, getMenu, updateMenu, addMenu, deleteMenu } from '@/api/menu'
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Menu',
  components: { TreeSelect: TreeSelect },
  data() {
    return {
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 表单参数
      form: {
        id: undefined,
        parentId: 0,
        name: undefined,
        meta: {
          icon: undefined,
          title: undefined
        },
        menuType: 'M',
        sort: undefined,
        hidden: false,
        component: undefined
      },
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 遮罩层
      loading: true,
      // 表单校验
      rules: {
        // fix: 表单验证状态不消失-->这里验证的字段名要和el-form-item中prop中的字段一致
        'meta.title': [
          { required: true, message: '菜单名称不能为空', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '菜单顺序不能为空', trigger: 'blur' }
        ],
        // path: [
        //   { required: true, message: '路由地址不能为空', trigger: 'blur' }
        // ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 处理表格 icon
    handleIcon(icon) {
      return icon === null ? 'null' : icon
    },
    /* 处理表格列中的 Boolean 类型
       列中每一行都会触发这个方法，row为table那一行数据保存的对象，index为索引。
    * */
    formatter(row, index) {
      return row.hidden ? '隐藏' : '显示'
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true
      getMenuList().then(response => {
        // this.menuList = this.handleTree(response.data, 'menuId')
        this.menuList = response.data
        this.loading = false
      })
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.meta === undefined ? node.name : node.meta.title,
        children: node.children
      }
    },
    /** 查询菜单下拉树结构 */
    getTreeSelect() {
      getMenuList().then(response => {
        this.menuOptions = []
        const menu = { id: 0, name: 'Main', meta: { title: '主类目' }, children: [] }
        menu.children = response.data
        this.menuOptions.push(menu)
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: 0,
        name: undefined,
        meta: {
          icon: undefined,
          title: undefined
        },
        menuType: 'M',
        sort: undefined,
        hidden: false,
        component: undefined
      }
      // this.resetForm('form')
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.getTreeSelect()
      if (row != null && row.id) {
        this.form.parentId = row.id
      } else {
        this.form.parentId = 0
      }
      this.open = true
      this.title = '添加菜单'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeSelect()
      getMenu(row.id).then(response => {
        this.form = response.data
        // 增加菜单类型，若无父节点则为 M-目录
        this.form.parentId === 0 ? this.form.menuType = 'M' : this.form.menuType = 'C'
        this.open = true
        this.title = '修改菜单'
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.meta.title + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return deleteMenu(row.id)
      }).then(() => {
        window.localStorage.removeItem('router')
        this.getList()
        this.$message.success('删除成功')
      }).catch((e) => {
        this.$message.error(e)
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateMenu(this.form).then(response => {
              this.$message.success('修改成功')
              window.localStorage.removeItem('router')
              this.open = false
              this.getList()
            }).catch((e) => {
              this.$message.error(e)
            })
          } else {
            if (this.form.component === undefined) {
              this.form.component = 'Layout'
            }
            addMenu(this.form).then(response => {
              this.$message.success('新增成功')
              window.localStorage.removeItem('router')
              this.open = false
              this.getList()
            }).catch((e) => {
              this.$message.error(e)
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    }
  }
}
</script>
